package com.erp.erp_servers.User.imp;

import com.erp.erp_dao.Department.IDepartmentDAO;
import com.erp.erp_dao.User.IUserDAO;
import com.erp.erp_entitys.Department.DepartmentEntity;
import com.erp.erp_entitys.Department.DepartmentExample;
import com.erp.erp_entitys.Email.email_custor;
import com.erp.erp_entitys.Menum.MenuEntity2;
import com.erp.erp_entitys.Menum.MenuEntity2Example;
import com.erp.erp_entitys.Menum.MenumEntity;
import com.erp.erp_entitys.Resource.ResourceEntity;
import com.erp.erp_entitys.Role.RoleEntity;
import com.erp.erp_entitys.Role.RoleExample;
import com.erp.erp_entitys.RoleGroup.RoleGroupEntity;
import com.erp.erp_entitys.RoleGroup.RoleGroupEntityExample;
import com.erp.erp_entitys.RoleGroupMember.RoleGroupMemberEntity;
import com.erp.erp_entitys.RoleGroupMember.RoleGroupMemberEntityExample;
import com.erp.erp_entitys.RoleLinkResource.RoleLinkResourceEntity;
import com.erp.erp_entitys.RoleLinkResource.RoleLinkResourceEntityExample;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.User.UserEntityExample;
import com.erp.erp_entitys.User.UserEntityVO;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.Menu.IMenuService;
import com.erp.erp_servers.Resource.IResourceService;
import com.erp.erp_servers.Role.IRoleService;
import com.erp.erp_servers.RoleGroup.IRoleGroupService;
import com.erp.erp_servers.RoleGroupMember.IRoleGroupMemberService;
import com.erp.erp_servers.RoleLinkResource.IRoleLinkResourceService;
import com.erp.erp_servers.User.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ImpUserSerice
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-06-23 12:51
 * @Version 1.0
 */
@Service
public class ImpUserSerice implements IUserService {

    @Autowired
    IUserDAO userDAO;
    @Autowired
    IRoleService roleService;
    @Autowired
    IResourceService resourceService;
    @Autowired
    IRoleLinkResourceService roleLinkResourceService;
    @Autowired
    IRoleGroupMemberService roleGroupMemberService;
    @Autowired
    IRoleGroupService roleGroupService;
    @Autowired
    IMenuService menuService;
    @Autowired
    IDepartmentDAO departmentDAO;
    @Autowired
      EmailService emailService;

    /**
     * 根据主键获取员工
     *
     * @param code
     * @return
     */
    @Override
    public UserEntity selectUserByCode(String code) {
        UserEntityExample example=new UserEntityExample();
        UserEntityExample.Criteria criteria = example.createCriteria();
         criteria.andCodeEqualTo(code);
        List<UserEntity> userEntities = userDAO.selectByExample(example);
        return userEntities.get(0);
    }

    /**
     * 获取部门下所有员工
     *
     * @param departmentCode
     * @return
     */
    @Override
    public List<UserEntity> selectByExample(String departmentCode) {
        UserEntityExample example=new UserEntityExample();
        UserEntityExample.Criteria criteria = example.createCriteria();
        criteria.andDepartmentCodeEqualTo(departmentCode);
        List<UserEntity> userEntities = userDAO.selectByExample(example);
        return userEntities;
    }

    /**
     * 获取员工
     *
     * @param departmentCode
     * @param name
     * @return
     */
    @Override
    public List<UserEntity> selectByExample(String departmentCode, String name) {
       /* UserEntityExample example=new UserEntityExample();
        UserEntityExample.Criteria criteria = example.createCriteria();
        
            criteria.andDepartmentCodeIn(getAllDepartmentCode(departmentCode));
      
        if(!name.equals(""))        criteria.andNameLike("%"+name+"%");
        List<UserEntity> userEntities = userDAO.selectByExample(example);*/
        List<UserEntity> userEntities = userDAO.selectAll(departmentCode, name);
        return userEntities;
    }
    private List<String> getAllDepartmentCode(String dcode){
        List<String> list = departmentDAO.selectByCode(dcode);
        return list;
    }

    /**
     * 根据条件获取员工
     *
     * @param example
     * @return
     */
    @Override
    public List<UserEntity> selectByExample(UserEntityExample example) {
        return userDAO.selectByExample(example);
    }

    @Override
    public Map<String, String> selectAll() {
        UserEntityExample example=new UserEntityExample();
        example.createCriteria();
        List<UserEntity> user = userDAO.selectByExample(example);
        Map<String, String> map=new HashMap<String, String>();
                for(int i=0;i<user.size();i++){
                    map.put(user.get(i).getCode(),user.get(i).getName());
                }
        return map;
    }

    @Override
    public List<UserEntity> getAllUser() {
        UserEntityExample example=new UserEntityExample();
        example.createCriteria();
        List<UserEntity> user = userDAO.selectByExample(example);
        return user;
    }

    @Override
    public List<UserEntity> selectUserByGroupCode(String gcode) {
        return userDAO.selectUserByGroupCode(gcode);
    }

    @Override
    public List<UserEntityVO> selectUserByGroup(String gcode) {
       // List<UserEntity> selectUserByGroupCode(String gcode);
      //  List<DepartmentEntity> selectByExample(DepartmentExample example);
        List<UserEntity> userEntities = userDAO.selectUserByGroupCode(gcode);
        List<String> list=new ArrayList<>();
        for(UserEntity ue:userEntities){
            list.add(ue.getDepartmentCode());
        }
        DepartmentExample example=new DepartmentExample();
        DepartmentExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIn(list);
        List<DepartmentEntity> departmentEntities = departmentDAO.selectByExample(example);
        Map<String,DepartmentEntity>map=new HashMap<>();
        for(DepartmentEntity dt:departmentEntities){
            map.put(dt.getCode(),dt);
        }
        List<UserEntityVO> vos=new ArrayList<>();
        for(UserEntity ue:userEntities){
            UserEntityVO vo=new UserEntityVO();
            vo.setCode(ue.getCode());
            vo.setName(ue.getName());
            vo.setDepartmentCode(ue.getDepartmentCode());
            //vo.setParentDepartmentEntity(map);
            String departMentName=map.get(ue.getDepartmentCode()).getName();
            vo.setDepartmentName(departMentName);
            vos.add(vo);
        }
        return vos;
    }


    /**
     * 根据主键删除用户
     *
     * @param id
     * @return
     */
    @Override
    public int deleteByPrimaryKey(String id) {

        return userDAO.deleteByPrimaryKey(id);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByExample(List<String> ids) throws Exception {
        UserEntityExample example=new UserEntityExample();
        UserEntityExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        //查询出要删除的用户
        List<UserEntity> userEntities = userDAO.selectByExample(example);
        List<email_custor> email_custors=new ArrayList<>();
        for(int i=0;i<userEntities.size();i++){
            UserEntity ue = userEntities.get(i);
            email_custor ec=new email_custor();
            ec.setStatue(0);
            ec.setCode(ue.getCode());
            ec.setCodeClass(0);
            ec.setHandle(2);
            ec.setName(ue.getName());
            ec.setNewEmail(ue.getEmail());
            ec.setOldEmail(ue.getEmail());
            email_custors.add(ec);
        }
        int num = userDAO.deleteByExample(example);
        if(num > 0){
            boolean tf = emailService.checkUserBox(email_custors);
            if(!tf){
                    throw new Exception("级联删除用户失败！");
            }
        }else{
            throw new Exception("删除用户失败！");
        }
        return num;
    }

    /**
     * 新增员工
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insertSelective(UserEntity record) throws Exception {
        int num = userDAO.insertSelective(record);
        List<email_custor> email_custors=new ArrayList<>();
            email_custor ec=new email_custor();
            ec.setStatue(0);
            ec.setCode(record.getCode());
            ec.setCodeClass(0);
            ec.setHandle(0);
            ec.setName(record.getName());
            ec.setNewEmail(record.getEmail());
            ec.setOldEmail(record.getEmail());
            email_custors.add(ec);
        if(num > 0){
            boolean tf = emailService.checkUserBox(email_custors);
            if(!tf){
                throw new Exception("级联新增用户失败！");
            }
        }else{
            throw new Exception("新增用户失败！");
        }
        return num;
    }

    /**
     * 根据主键更新用户
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(UserEntity record) throws Exception {
        UserEntity ue = userDAO.selectByPrimaryKey(record.getId());
        int num = userDAO.updateByPrimaryKeySelective(record);

        List<email_custor> email_custors=new ArrayList<>();
        email_custor ec=new email_custor();
        ec.setStatue(0);
        ec.setCode(record.getCode());
        ec.setCodeClass(0);
        ec.setHandle(1);
        ec.setName(record.getName());
        ec.setNewEmail(record.getEmail());
        ec.setOldEmail(ue.getEmail());
        email_custors.add(ec);
        if(num > 0){
            boolean tf = emailService.checkUserBox(email_custors);
            if(!tf){
                throw new Exception("级联更新用户失败！");
            }
        }else{
            throw new Exception("更新用户失败！");
        }
        return num;
    }

    /**
     * 获取当前用户的所有权限
     *
     * @param user
     * @return
     */
    @Override
    public List<RoleEntity> getAllRoleByUserCode(UserEntity user) {
        List<RoleEntity> listRole=new ArrayList<RoleEntity>();
        //当前用户的所有角色、角色组
        String roles=user.getRoles();
        if(roles == null ) return  listRole;
        String[] rolesList=roles.split(",");

        RoleEntity re=new RoleEntity();
        //所有角色
        List<RoleEntity> roleEntities = roleService.selectByExample(re);
       Map<String,RoleEntity> map=new HashMap<String, RoleEntity>();
        for(int i=0;i<roleEntities.size();i++){
            map.put(roleEntities.get(i).getCode(),roleEntities.get(i));
        }
        //获取角色组成员列表
        RoleGroupMemberEntity record2=new RoleGroupMemberEntity();
        List<RoleGroupMemberEntity> roleGroupMemberEntities = roleGroupMemberService.selectByExample(record2);
        List<String> list=new ArrayList<String>();
        for(int i=0;i<roleGroupMemberEntities.size();i++){
            for(int n=0;n<rolesList.length;n++){
                if(rolesList[n].equals(roleGroupMemberEntities.get(i).getRoleCode()) || rolesList[n].equals(roleGroupMemberEntities.get(i).getGroupCode())){
                    list.add(roleGroupMemberEntities.get(i).getRoleCode());
                }
            }

        }
        String[] strs=roles.split(",");
        for(int i=0;i<strs.length;i++){
            list.add(strs[i]);
        }

        for(int i=0;i<list.size();i++){
            listRole.add(map.get(list.get(i)));
        }

        return listRole;
    }

    /**
     * 获取用户所有菜单
     *
     * @param user
     * @return
     */
    @Override
    public List<MenumEntity> getAllResourceByUser(UserEntity user) {
        //用户所具有的角色
       List<RoleEntity> allRoleByUserCode = this.getAllRoleByUserCode(user);
        List<String> listRoles=new ArrayList<String>();
       for(RoleEntity re:allRoleByUserCode){
            if(re.getType()==1)
            listRoles.add(re.getCode());
        }
        //取所有资源与角色关联列表
        RoleLinkResourceEntity rlre=new RoleLinkResourceEntity();
        List<RoleLinkResourceEntity> roleLinkResourceEntities = roleLinkResourceService.selectByExample2(listRoles,rlre);
       List<String> list=new ArrayList<String>();
      for(int i=0;i<roleLinkResourceEntities.size();i++){
           list.add(roleLinkResourceEntities.get(i).getResourceCode());
       }
        //所有资源列表
        ResourceEntity record =new ResourceEntity();
        List<ResourceEntity> res= resourceService.selectByExample(record);//所有资源列表
        Map<String,MenumEntity> map=new HashMap<String ,MenumEntity>();
        for(int i=0;i<res.size();i++){
            map.put(res.get(i).getCode(),this.conver(res.get(i)));
        }
        List<ResourceEntity> resourceEntities= resourceService.selectByExample(list);//用户所具有的资源
        /////////////////////////////////////
       /* List<ResourceEntity> resourceEntities=new ArrayList<ResourceEntity>();
        for(int i=0;i<resourceEntitie.size();i++){
            if(resourceEntitie.get(i).getLevel()==2){
                resourceEntities.add(resourceEntitie.get(i));
            }
        }*/
                //////////////////////////////////
        //根据资源code组装资源树
        List<MenumEntity> listMnu=new ArrayList<MenumEntity>();
        List<MenumEntity> sublist=new ArrayList<MenumEntity>();
        for(int i=0;i<resourceEntities.size();i++){
           MenumEntity re=this.conver(resourceEntities.get(i));
           listMnu.add(re);
          /* if(i < ( resourceEntities.size()-1)){
               MenumEntity re2=this.conver(resourceEntities.get(i+1));
               String path1=re.getPath().substring(0,re.getPath().lastIndexOf("/"));
               String path2=re2.getPath().substring(0,re2.getPath().lastIndexOf("/"));
               if(path1.equals(path2)){
                   sublist.add(re);
                   continue;
               }else{
                   sublist.clear();
               }
           }else{

           }
            sublist.add(re);
           if(! re.getCode().equals("0")){
               map.get(re.getPid()).setList(sublist);
               re=this.getParentTree(map.get(re.getPid()),map);
               listMnu.add(re);
           }else{
               listMnu.add(re);
           }*/
       }
        return listMnu;
    }

    @Override
    public List<MenuEntity2> getAllResourceByUser2(UserEntity user) {
        String roles = user.getRoles();//取用户所有角色code
        if(null ==roles || roles.equals("")) {
            List<MenuEntity2> re_list=new ArrayList<>();
            return re_list;
        }
        String[] roleall=roles.split(",");
        List<String> listrolecode=new ArrayList<String>();//所有角色code列表
        for(int i=0;i<roleall.length;i++){
            listrolecode.add(roleall[i]);
        }
        RoleExample example=new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIn(listrolecode);
        List<RoleEntity> roleEntities = roleService.selectByExample(example);//获取用户所有的角色
        //取所有角色组
        RoleGroupEntityExample example_rolegroup=new RoleGroupEntityExample();
        RoleGroupEntityExample.Criteria criteria1 = example_rolegroup.createCriteria();
        criteria1.andCodeIn(listrolecode);
        List<RoleGroupEntity> roleGroupEntities = roleGroupService.selectByExample(example_rolegroup);
        //取角色组code
        List<String> list_groupcode=new ArrayList<String>();
        for(int i=0;i<roleGroupEntities.size();i++){
            list_groupcode.add(roleGroupEntities.get(i).getCode());
        }
        //根据角色组code列表取其下所有角色
        List<RoleGroupMemberEntity> roleGroupMemberEntities=new ArrayList<RoleGroupMemberEntity>();
        if(!list_groupcode.isEmpty()){
            RoleGroupMemberEntityExample example_rgm=new RoleGroupMemberEntityExample();
            RoleGroupMemberEntityExample.Criteria criteria2 = example_rgm.createCriteria();
            criteria2.andGroupCodeIn(list_groupcode);
            roleGroupMemberEntities = roleGroupMemberService.selectByExample(example_rgm);
        }

        List<String> list_rgm=new ArrayList<String>();
        for(int i=0;i<roleGroupMemberEntities.size();i++){
            list_rgm.add(roleGroupMemberEntities.get(i).getRoleCode());
        }
        List<RoleEntity> rgms=new ArrayList<RoleEntity>();
        criteria.getAllCriteria().clear();//清空
        if(!list_rgm.isEmpty()){
            criteria.andCodeIn(list_rgm);
            rgms = roleService.selectByExample(example);//角色组下所有角色
        }

        //合并所有角色roleEntities
        for(int i=0;i<rgms.size();i++){
            roleEntities.add(rgms.get(i));
        }
        //取所有角色code列表
        List<String> rolecodeAll=new ArrayList<String>();
        for(int i=0;i<roleEntities.size();i++){
            rolecodeAll.add(roleEntities.get(i).getCode());
        }
        if(rolecodeAll.isEmpty()){
            return null;
        }
        //取角色对应的菜单code
        List<String> zycodes=new ArrayList<String>();//资源code列表
        RoleLinkResourceEntityExample example_zy=new RoleLinkResourceEntityExample();
        RoleLinkResourceEntityExample.Criteria criteria3 = example_zy.createCriteria();
        criteria3.andRoleCodeIn(rolecodeAll);
        List<RoleLinkResourceEntity> roleLinkResourceEntities = roleLinkResourceService.selectByExample(example_zy);
        for(int i=0;i<roleLinkResourceEntities.size();i++){
            zycodes.add(roleLinkResourceEntities.get(i).getResourceCode());
        }
        //取菜单code列表对应的菜单
        MenuEntity2Example exampleme=new MenuEntity2Example();
        MenuEntity2Example.Criteria criteria4 = exampleme.createCriteria();
        criteria4.andCodeIn(zycodes);
        List<MenuEntity2> menuEntity2s = menuService.selectByExample(exampleme);
        //取菜单url（即资源code）列表
        List<String> menucodes=new ArrayList<String>();
        for(int i=0;i<menuEntity2s.size();i++){
            menucodes.add(menuEntity2s.get(i).getCode());
        }

        List<MenuEntity2> tree = menuService.getTree();//菜单树
        //从菜单树中去除不在code列表中的菜单

            MenuEntity2 me=tree.get(0);
            me.setList(this.qc(me.getList(),menucodes));
            //me.setList(this.qc(me.getList(),menucodes));
        return tree;
    }
  private List<MenuEntity2> qc(List<MenuEntity2> sub,List<String> menucodes){

      List<MenuEntity2> list=new ArrayList<MenuEntity2>();//
        for(int i=0;i<sub.size();i++){
            MenuEntity2 me = sub.get(i);
            String code=me.getCode();
            boolean tf=false;
            if(me.getList().size() >0){
               me.setList(this.qc(me.getList(),menucodes));
            }
                for(int n=0;n<menucodes.size();n++){
                    if(menucodes.get(n).equals(code)){
                        tf=true;
                        break;
                    }
                }

            if(tf || me.getList().size()>0) list.add(me);//从树中移除不在code列表中的

        }

        return list;
  }
    private MenumEntity conver(ResourceEntity re){
    MenumEntity me=new MenumEntity();
    me.setId(re.getId());
    me.setPid(re.getPid());
    me.setCode(re.getCode());
    me.setUrl(re.getUrl());
    me.setPath(re.getPath());
    me.setLevel(re.getLevel());
    me.setName(re.getName());
    return me;
}
    /**
     * 递归获取菜单树
     * @param m
     * @param map
     * @return
     */
    private MenumEntity getParentTree(MenumEntity m, Map<String, MenumEntity> map){
        String pid=m.getPid();
        MenumEntity me=new MenumEntity();
        if(! map.get(pid).getCode() .equals("0")){
            List<MenumEntity> list=new ArrayList<MenumEntity>();
            list.add(m);
            map.get(pid).setList(list);
            me= this.getParentTree(map.get(pid), map);

        }else{
            me=map.get(pid);
            List<MenumEntity> list=new ArrayList<MenumEntity>();
            list.add(m);
            me.setList(list);
        }
        return me;
    }

    /**
     * 根据父节点获其下子菜单
     *
     * @param pid
     * @return
     */
    @Override
    public List<ResourceEntity> getMenumByPid(String pid) {
        ResourceEntity record =new ResourceEntity();
        record.setPid(pid);
        List<ResourceEntity> res= resourceService.selectByExample(record);
        return res;
    }

    @Override
    public List<UserEntity> getAllUserNameAndCode() {
        return userDAO.getAllUserNameAndCode();
    }
    @Override
    public List<UserEntity> selectDimUser(String dim) {
        List<UserEntity> list = userDAO.selectDimUser(dim);
        return list;
    }

    /**
     * 通过用户编码集合获取用户信息
     * @param codes 用户编码集合
     * @return 用户信息
     */
    @Override
    public List<UserEntity> getUserByUserCodeList(List<String> codes) {
        return userDAO.getUserByUserCodeList(codes);
    }

}
